<?php


namespace App\Services;

use App\Models\FileGoods;
use App\Models\FileGoodsError;
use Illuminate\Support\Facades\DB;
use App\Jobs\ImportGoods;
use App\Imports\GoodsImport;
use Illuminate\Http\UploadedFile;
use App\Utils\Code;
use Illuminate\Support\Str;

class GoodsImportService extends BaseService
{
    public function importGoods(UploadedFile $file, array $params = []) {
        if (FileGoods::where('status', 0)->exists()) {
            throw new \Exception('检测到已有表格导入数据正在执行，为避免重复出错，请在上一个导表执行完毕后再导入新表', Code::PARAMETER_ERROR);
        }
        return \DB::transaction(function () use ($file, $params) {
            $fileName = Str::random(40).'.'.$file->getClientOriginalExtension();
            $datePath = date('Y/m/d');
            $fileInfo = new FileGoods();
            $fileInfo->user_id = $this::$user->user_id;
            $fileInfo->name = $file->getClientOriginalName();
            $fileInfo->path = $file->storeAs($datePath, $fileName, ['disk'=>'excel']);
            $fileInfo->status = 0;
            $fileInfo->save();
    
            $filePath = public_path("/storage/excels/{$fileInfo->path}");
            if (isset($params['image']) && $params['image']) {
                $reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
                $spreadsheet = $reader->load($file);
                $sheet = $spreadsheet->getActiveSheet();
                $draws = $sheet->getDrawingCollection();
                $imageDirPath = public_path('storage/images/'.$datePath);
                if (!is_dir($imageDirPath)) {
                    mkdir($imageDirPath, 0777, true);
                }
                foreach($draws as $drawing) {
                    $originImageFileName = 'storage/images/'.$datePath.'/'.$drawing->getHashCode();
                    $imageFileName = $imageDirPath.'/'.$drawing->getHashCode();
                    switch ($drawing->getExtension()) {
                        case 'jpg':
                        case 'jpeg':
                            $imageFileName .= '.jpeg';
                            $originImageFileName .= '.jpeg';
                            $source = imagecreatefromjpeg($drawing->getPath());
                            imagejpeg($source,  $imageFileName);
                            break;
                        case 'gif':
                            $imageFileName .= '.gif';
                            $originImageFileName .= '.gif';
                            $source = imagecreatefromgif($drawing->getPath());
                            imagegif($source,  $imageFileName);
                            break;
                        case 'png':
                            $imageFileName .= '.png';
                            $originImageFileName .= '.png';
                            $source = imagecreatefrompng($drawing->getPath());
                            imagepng($source, $imageFileName);
                            break;
                    }
                    $coordi = $drawing->getCoordinates();
                    $sheet->setCellValue($coordi, $originImageFileName);
                }
                $writer = new \PhpOffice\PhpSpreadsheet\Writer\Xlsx($spreadsheet);
                $writer->save($filePath);
                if (isset($params['mode']) && $params['mode'] == 'async') {
                    ImportGoods::dispatch($fileInfo);
                } else {
                    \Excel::import(new \App\Imports\GoodsImport($fileInfo), $filePath);
                    $fileInfo->status = 1;
                    $fileInfo->save();
                }
            } else {
                if (isset($params['mode']) && $params['mode'] == 'async') {
                    ImportGoods::dispatch($fileInfo);
                } else {
                    \Excel::import(new \App\Imports\GoodsImport($fileInfo), $filePath);
                    $fileInfo->status = 1;
                    $fileInfo->save();
                }
            }
            return FileGoods::where('file_id', $fileInfo->file_id)->first();
        });
    }
    
    /**
     * 商品文件分页
     * @param array $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function filePaginate(array $params = []) {
        $model = new FileGoods();
        if (key_exists('status', $params) && is_numeric($params['status'])) {
            $model = $model->where('status', $params['status']);
        }
        if (isset($params['type']) && $params['type']) {
            $model = $model->where('type', $params['type']);
        }
        if (isset($params['created_at']) && $params['created_at'] && is_array($params['created_at'])) {
            if (isset($params['created_at'][0]) && $params['created_at'][0]) {
                $model = $model->where('created_at', '>=', $params['created_at'][0]);
            }
            if (isset($params['created_at'][1]) && $params['created_at'][1]) {
                $model = $model->where('created_at', '<=', $params['created_at'][1]);
            }
        }
        return $model->orderBy('file_id', 'desc')
            ->paginate(isset($params['per_page']) ? (int)$params['per_page'] : null);
    }
    
    /**
     * 商品导入错误日志
     * @param array $params
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function errorPaginate(array $params = []) {
        $model = new FileGoodsError();
        if (isset($params['file_id']) && $params['file_id']) {
            $model = $model->where('file_id', $params['file_id']);
        }
        if (isset($params['created_at']) && $params['created_at'] && is_array($params['created_at'])) {
            if (isset($params['created_at'][0]) && $params['created_at'][0]) {
                $model = $model->where('created_at', '>=', $params['created_at'][0]);
            }
            if (isset($params['created_at'][1]) && $params['created_at'][1]) {
                $model = $model->where('created_at', '<=', $params['created_at'][1]);
            }
        }
        return $model->orderBy('file_id', 'desc')
            ->paginate(isset($params['per_page']) ? (int)$params['per_page'] : null);
    }
}
